/**
 * 在屏幕上放置一个元素，在1s内点击3次，显示 vConsole
 *
 * @param {Object} config
 */
/* global VConsole */
window.panxVConsole = function panxVConsole(config) {
  const TIME = +new Date();
  const VC_CDN = `https://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/vconsole/3.0.0/vconsole.min.js?v${TIME}`;
  let VC_INSTANCE = null;

  function injectVConsole() {
    const consoleScript = document.createElement('script');
    consoleScript.src = VC_CDN;
    document.head.appendChild(consoleScript);
    consoleScript.onload = function initVConsole() {
      console.warn('init vConsole');
      VC_INSTANCE = new VConsole();
    };
    consoleScript.onerror = function loadVConsoleError() {
      console.error('failed load vConsole');
    };
  }

  function injectTrigger() {
    const triggerElem = document.createElement('div');
    triggerElem.style.height = config.height || '30px';
    triggerElem.style.width = config.width || '30px';
    triggerElem.style.zIndex = '100000';
    triggerElem.style.position = 'fixed';
    triggerElem.style.backgroundColor = config.bgColor || 'transparent';
    triggerElem.style.opacity = '0.5';
    triggerElem.dataset.clickCount = '0';
    if (config.left) triggerElem.style.left = config.left;
    if (config.right) triggerElem.style.right = config.right;
    if (config.top) triggerElem.style.top = config.top;
    if (config.bottom) triggerElem.style.bottom = config.bottom;
    triggerElem.onclick = function checkClick(event) {
      const clickCount = Number(this.dataset.clickCount) + 1;
      this.dataset.clickCount = clickCount;
      if (clickCount === 2 && ! VC_INSTANCE) {
        injectVConsole();
      }
      // should click 3 times in 1000ms
      setTimeout(() => {
        triggerElem.dataset.clickCount = '0';
      }, 1000);
      event.stopPropagation();
    };
    document.body.appendChild(triggerElem);
  }

  injectTrigger();
};

